<template>
  <div :style="{ fontSize:fontSize + 'px'}" style="background: rgb(237, 241, 245);background: #EDF1F5" class="laboratory">
    <v-noticebar></v-noticebar>
    <v-header 
      :back="false" 
      v-on:clickRightIcon="$router.push('/laboratory/new')" 
      title="宽客实验室"
      :size="18"
      ref="labheader"
      rightText="创建实验">
    </v-header>
    <tab v-model="idx"
         defaultColor="rgba(102, 102, 102, 0.5)"
         active-color="#4D63EB"
         style="position: fixed;top: 61px;width: 100%;z-index: 999"
         class="tabAfter"
         custom-bar-width="50px">
      <tab-item class="tabOne">往期实验</tab-item>
      <tab-item>正在测试</tab-item>
    </tab>
    <div>
    <mt-tab-container
      style="margin-top: 97px; height:100%;transition: transform 0.3s" 
      v-model="idx">
      <mt-tab-container-item :id="0"
        :style="{ minHeight: offsetHeight + 'px' }">
        <v-networkerr v-if="!hasHistoryLabCache" v-on:reload="reloadData"></v-networkerr>
        <div v-else>
          <div class="historyLab" style="position: fixed;height: 60%;width: 100%;display: flex;justify-content: center;align-items: center;margin-top: 80px;font-size: 1.6em;" 
              v-if="historyLabLen === 0">
              <div class="progressing">
                还没有已完成实验策略，
              <div style="color: #4D66FF;display: inline" @click="$router.push('/laboratory/new')">再创建一个</div>
              </div>
          </div>
          <v-scroller 
            height="-154px"
            :lockY="locky"
            v-on:reload="findHistoryLab"
            ref="scrollBar"
            class="historyLab" v-else>
          <swipeout class="progressing">
            <swipeout-item
              :auto-close-on-button-click="false"
              v-for="(value, key) in historyLab"
              v-if="value.progress === 100"
              :threshold=".2"
              underlay-color="#ccc"
              :ref="'swipeout' + key"
              v-on:move="locky = true"
              v-on:end="locky = false"
              :key="value.id">
              <div slot="right-menu">
                <swipeout-button background-color="#FC3733" @click.native="clickRightBtn('deleteHistory', value, key)">删除</swipeout-button>
              </div>
              <div slot="content" class="vux-1px-tb progressLab">
              <div class="processName">
                <div>{{value.name}}</div>
                <div class="createTime"><div style="display: inline-block;color: #666">创建时间</div>: {{value.created_time | timeFilter }}</div>
              </div>
              <div class="complateBtn">
                <a @click="gotoDetail(value)">查看结果</a>
              </div>
              </div>
            </swipeout-item>
          </swipeout>
          </v-scroller>
        </div>
      </mt-tab-container-item>
      <mt-tab-container-item :style="{ minHeight: offsetHeight + 'px' }" :id="1">
        <v-networkerr v-if="!hasHistoryLabCache" v-on:reload="findHistoryLab"></v-networkerr>
        <div v-else>
        <div class="historyLab" style="position: fixed;height: 60%;width: 100%;display: flex;justify-content: center;align-items: center;margin-top: 80px;font-size: 1.6em;" 
          v-if="newLabLen === 0">
          <div class="progressing">
            还没有测试中实验策略，
          <div style="color: #4D66FF;display: inline" @click="$router.push('/laboratory/new')">创建一个</div>
          </div>
        </div>
        <v-scroller 
            height="-154px"
            :lockY="locky"
            v-on:reload="findHistoryLab"
            ref="scrollBar"
            class="historyLab" v-else>
          <swipeout class="progressing">
            <swipeout-item
              :ref="'swipeout' + key"
              transition-mode="follow"
              :auto-close-on-button-click="false"
              v-for="(value, key) in historyLab"
              :threshold=".2"
              underlay-color="#ccc"
              v-if="value.progress !== 100"
              :key="value.id">
              <div slot="right-menu">
                <swipeout-button background-color="#FC3733" @click.native="clickRightBtn('delete', value, key)">删除</swipeout-button>
              </div>
              <div slot="content" class="vux-1px-tb progressLab">
                <div class="processName processProcessTime">
                  <div>{{value.name}}</div>
                  <sub class="createTime"><div style="display: inline-block;color: #666">创建时间</div>: {{value.created_time | timeFilter }}</sub>
                </div>
                <div class="processProcess">
                  <div>火速测试中</div>
                </div>
              </div>
            </swipeout-item>
          </swipeout>
        </v-scroller>
        </div>
      </mt-tab-container-item>
    </mt-tab-container>
    </div>
    <actionsheet
      v-model="isActionSheet"
      :menus="{
        menu1: '删除'
      }"
      @on-click-mask="cancelMask"
      @on-click-menu="labDelete">
    </actionsheet>
  </div>
</template>

<script>
import { Swipeout, SwipeoutItem, SwipeoutButton } from '../../components/common/swipeout'
import { Tab, TabItem, Datetime, Actionsheet } from 'vux'
import { TabContainer, TabContainerItem, Toast, MessageBox, Picker, Popup } from 'mint-ui'
import plugins from '../../plugins/'

export default {
  name: 'laboratory',
  components: {
    Tab,
    TabItem,
    Datetime,
    Swipeout,
    SwipeoutItem,
    SwipeoutButton,
    Actionsheet
  },
  data () {
    return {
      fontSize: 10,
      selected: '0',
      idx: 0,
      isActionSheet: false,
      actionsheetId: '', // 点击删除lab对应的ID
      hasHistoryLabCache: true,
      selectedLabIdx: {},
      historyLab: {},
      networkState: 'online',
      offsetHeight: 667,
      historyLabLen: 0,
      newLabLen: 0,
      locky: false
    }
  },
  watch: {
    '$store.state.reload': function (val) {
      if (this.$route.path === '/laboratory') this.idx === 0 ? this.idx = 1 : this.idx = 0
    },
    idx: function (val) {
      this.$nextTick(() => {
        this.$refs.scrollBar.$refs.scrollBar.reset()
        this.$refs.scrollBar.$refs.scrollBar.donePulldown()
      })
    }
  },
  mounted () {
    document.addEventListener("backbutton", this.exitApp, false);
  },
  beforeRouteEnter (to, from, next) {
    next((vm) => {
      vm.$refs.scrollBar.$refs.scrollBar.donePulldown()
    })
  },
  methods: {
    // onBackKeyDown () {
    //     document.removeEventListener("backbutton", this.onBackKeyDown, false);
    //     document.addEventListener("backbutton", this.exitApp, false);
    //   },
    exitApp () {
      navigator.app.exitApp();
    },
    getIab () {
      // if (!this.$store.state.networkState) {
      //   this.$plugins.networkErr()
      //   this.getIabByCache(this.$config.cacheTime.offlineCache)
      //   this.postLab.quantity = null
      //   this.postLab.name = '',
      //   this.postLab.startDate = '',
      //   this.postLab.endDate = '',
      //   this.postLab.country = ''
      //   return
      // }
      // window.localStorage.getItem('lab') ? this.getIabByCache(this.$config.cacheTime.onlineCache) : this.getIabByNetwork()
      // this.$set(this.postLab, 'country', '')
      // this.$set(this.postLab, 'stockPool', '')
      // this.$set(this.postLab, 'optMethod', '')
      // this.postLab.quantity = null
      // this.postLab.name = '',
      // this.postLab.startDate = '',
      // this.postLab.endDate = '',
      // this.postLab.country = ''
    },
    labDelete (menuKey, menuItem) {
      if (menuKey === 'cancel') return
      this.baseService.post('lab/del', {id: this.actionsheetId}).then((res) => {
        Toast({
          message: '删除成功',
          duration: 1000
        })
        this.$refs[`swipeout${this.selectedLabIdx}`][0].close()
        setTimeout(() => {
          this.historyLab[this.selectedLabIdx].progress === 100 ? this.historyLabLen-- : this.newLabLen--
          this.historyLab.splice(this.selectedLabIdx, 1)
        }, 300)
      })
    },
    cancelMask () {
      this.$refs[`swipeout${this.selectedLabIdx}`][0].close()
    },
    clickRightBtn (val, value, key) {
      this.selectedLabIdx = key
      val === 'delete' ? this.selectedLabType = 'process' : this.selectedLabType = 'history'
      this.isActionSheet = true
      this.actionsheetId = value.id
    },
    getIabByNetwork () {
      // this.baseService.get('/lab/v1.1/para').then((res) => {
      //   this.networkState = 'online'
      //   Object.keys(res.data).forEach((item, idx) => {
      //     this.step.obj[idx] = false
      //     if (item === 'style') {
      //       if (this.$store.state.lab.style) {
      //         res.data.style = this.$store.state.lab.style
      //         Object.keys(res.data.style).forEach((item, idx) => {
      //           if (res.data.style[item].isActive) this.isOk = true
      //         })
      //         this.isOk === true ? this.step.obj[0] = true : ''
      //       } else {
      //         Object.keys(res.data[item]).forEach((key, idx) => {
      //           res.data[item][key] = {
      //             title: res.data[item][key],
      //             isActive: false
      //           }
      //         })
      //       }
      //       return
      //     }
      //   })
      //   this.lab = res.data
      //   plugins.cacheControl.setCache('lab', this.lab)
      // })
    },
    getIabByCache (min) {
      // this.$plugins.cacheControl.getCache('lab', min).then((res) => {
      //   this.lab = res.data
      // }).catch((err) => {
      //   // TODO: 无缓存且无网络
      //   // if (!this.$state.store.networkErr) window.alert('网络连接失败')
      //   if (!this.$store.state.networkState) this.networkState = 'offline'
      //   this.getIabByNetwork()
      // })
    },
    countLabLen (obj) {
      this.newLabLen = this.historyLabLen = 0
      obj.forEach((item, idx) => {
        item.progress === 100 ? this.historyLabLen++ : this.newLabLen++
      })
    },
    findHistoryLab (checkIdx = false) {
      if (!this.$store.state.networkState) {
        this.$plugins.networkErr()
        this.$plugins.cacheControl.getCache('historyLab', this.$config.offlineCache).then((res) => {
          this.hasHistoryLabCache = true
          this.countLabLen(res.data)
          this.historyLab = res.data
          this.$nextTick(() => {
            this.$refs.scrollBar.$refs.scrollBar.reset()
          })
        }).catch((e) => {
          this.hasHistoryLabCache = false
        })
        return
      }
      this.baseService.get('/lab/history').then((res) => {
        this.hasHistoryLabCache = true
        this.countLabLen(res.data)
        this.historyLab = res.data
        this.$plugins.cacheControl.setCache('historyLab', res.data)
        if (checkIdx) {
          this.historyLab.forEach((item, idx) => {
            if (item.name === this.$route.query.lab_name) item.progress === 100 ? this.idx = 0 : this.idx = 1
          })
        }
        this.$nextTick(() => {
          this.$refs.scrollBar.$refs.scrollBar.reset()
        })
       }).catch((err) => {
         if (err === 'timeout') {
            this.$plugins.cacheControl.getCache('historyLab', this.$config.cacheTime.offlineCache).then((res) => {
              this.hasHistoryLabCache = true
              this.countLabLen(res.data)
              this.historyLab = res.data
            }).catch((err) => {
              this.hasHistoryLabCache = false
            })
          }
       })
    },
    seeHistory () {
      this.idx = 0
    },
    gotoDetail (value) {
      this.$router.push({path: 'laboratoryDetail',query: {id: `${value.id}`}})
    }
  },
  created () {
    this.fontSize = this.fontSize * document.body.offsetWidth / 320
    this.offsetHeight = document.body.offsetHeight - 108
    this.getIab()
    this.findHistoryLab()
  },
  activated () {
    if (this.$route.query.lab_name) this.findHistoryLab(true)
  },
  mounted () {
    this.$refs.labnameinput.addEventListener('focus', () => {
      this.$refs.labheader.$el.style.position = 'absolute'
    })
    this.$refs.labnameinput.addEventListener('blur', () => {
      this.$refs.labheader.$el.style.position = 'fixed'
    })
    document.getElementsByClassName('weui-mask_transparent')[0].addEventListener('touchmove', (e) => {
      e.preventDefault()
    })
  },
  filters: {
    timeFilter (val) {
      let newVal = ''
      val = val.split(':')
      newVal = val[0] + ':' + val[1]
      return newVal
    }
  }
}
</script>

<style scoped lang="less">
.processProcessTime {
  display: flex;
  flex-direction: column;
  sub {}
}
.vux-number-input {
  font-size: 1.2rem !important;
}
.nextStep {
  height: 4.6em !important;
  width: 96% !important;
}
.iconsize {
  font-size: 1.8em;
}
.laboratoryClass {
  height: 140%;
}
.historyLab {
  background: #EDF1F5;
  .progressing {
    margin-bottom: 10em;
    .tip {
      font-size: 1.2em;
    }
    .complateBtn {
      padding: 0.8em 1.6em;
      color: white;
      border-radius: 10px;
      background: #7590FF;
    }
    .progressLab {
      height: 6em;
      display: flex;
      justify-content:center;
      align-items: center;
      background: white;
      padding: 0 1.5em;
      position: relative;
      margin-bottom: 1px;
      .createTime {
        font-size: 0.8em;
        color: rgba(102,102,102,0.50);
      }
      .processProcess {
        font-size: 2em;
        width: 40% !important;
      }
      .processName {
        font-size: 1.4em;
        flex: 7;
      }
      .processLine {
        height: 3px;
        background: #4D66FF;
        position: absolute;
        bottom: 0;
        left: 0;
        border-radius: 25px;
      }
    }
    .progressLab {
      height: 6em;
      display: flex;
      justify-content:center;
      align-items: center;
      border-bottom: 1px solid #eee;
      background: white;
      padding: 0 1.5em;
      position: relative;
      .processProcess {
        font-size: 1.3em;
        text-align: right;
        div {
          background: #FE7A4A;
          text-align: center;
          display: inline-flex;
          color: white;
          border-radius: 10px;
          justify-content: center;
          width: 60%;
          padding: 0.5em 0.8em;
        }
      }
      .processName {
        font-size: 1.4em;
        flex: 1;
      }
      .processLine {
        height: 3px;
        background: #4D66FF;
        position: absolute;
        bottom: 0;
        left: 0;
        border-radius: 25px;
      }
    }
  }
}
.stepStr {
  font-size: 1.6em;
  display: block;
  text-align: center;
  margin: 1em 0 1.6em 0;
}
.strategyStyle {
  width: 100%;
  .strategyBtn {
    flex: 1;
    width: 46% !important;
    margin: 2% !important;
    height: 5em !important;
    display: inline-flex;
    margin: 0;
  }
}

.lab_name {
  width: 94%;
  height: 3.4em;
  border: 0px solid #000;
  border-radius: 10px;
  font-size: 1.2em;
  padding: 0 3%;
  margin: 0 auto;
}
.nextStepBtn {
  display: inline-flex !important;
  width: 48% !important;
  margin: 0 !important;
}
.nextStepBtn:nth-child(1) {
  margin-right: 2% !important;
}
.lastStep {
  text-align: center;
  .title {
    color: #4D66FF;
    font-size: 2em;
    margin-bottom: 0.3em;
  }
  .desc {
    font-size: 1em;
  }
  img {
    display: block;
    width: 19em;
    height: 18em;
    margin: 2em auto;
  }
}
._options {
  width: 100%;
  height: 3.4em;
  background: #FFFFFF;
  border-radius: 10px;
  display: flex;
  justify-content: center;
  align-items: center;
  margin: 1em 0;
  .key {
    flex: 1.5;
    display: flex;
    justify-content: center;
    align-items: center;
    font-size: 1.4em;
    color: #666;
    position: relative;
    &:after {
      content: '';
      background: #E9E9E9;
      height: 1.3em;
      position: relative;
      width: 1px;
      position: absolute;
      right: 0;
      top: 0;
    }
  }
  .value {
    flex: 3;
    display: flex;
    justify-content: flex-start;
    padding-left: 1.8em;
    align-items: center;
    position: relative;
    font-size: 1.4em;
    color: #666;
  }
}
.tabAfter {
  border-top: 1px solid #E9E9E9;
  .tabOne {
    position: relative;
  }
  .tabOne:after {
    content: '';
    height: 14px;
    width: 1px;
    background: #eee;
    display: block;
    position: absolute;
    top: 15px;
    right: 0;
  }
}

.weui-cell:before {
  content: '';
  border-top: 0px solid white;
}

.btnBox {
  display: flex;
  flex-direction: row;
  margin-top: 0.8em;
  margin-bottom: 8em;
  div {
    flex: 1;
  }
}
.laboratoryClass {
}
.mint-tab-container-item{
  background: #EDF1F5;
}
</style>
